package com.yangluyao.easyexcel.read.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.xiaoleilu.hutool.util.StrUtil;
import com.yangluyao.easyexcel.model.ExcelInfo;
import com.yangluyao.easyexcel.model.QualityUser;
import com.yangluyao.easyexcel.service.IQualityUserService;
import com.yangluyao.easyexcel.utils.ApiResponse;
import com.yangluyao.easyexcel.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/*
* @Description: TODO 导入监听类
* @Author:  hejiayao
* @CreateDate:  2021/7/2 14:51
* @UpdateUser:  hejiayao
* @UpdateDate:  2021/7/2 14:51
* @className: EasyExcelReadListener
* @Package : com.yangluyao.easyexcel.read.listener
* @Version: 1.0
*/
@Slf4j
public class QualityUserListener extends AnalysisEventListener<QualityUser> {


    private static final Logger LOGGER = LoggerFactory.getLogger(QualityUserListener.class);



    private IQualityUserService qualityUserService;

    private List<QualityUser> qualityUserList = new ArrayList<>();


    private final List<QualityUser> errList = new ArrayList<>();

    //导入excel返回信息
    private final ExcelInfo excelInfo = new ExcelInfo();

    /**
     * 错误集合
     */
    private final StringBuffer errMessage = new StringBuffer();

    private final ApiResponse response;


    public QualityUserListener(IQualityUserService qualityUserService,ApiResponse apiResponse) {
        this.qualityUserService = qualityUserService;
        this.response = apiResponse;
    }

    /*
     * 在invoke() 中，我们将数据封装到 list中.
     * 在控制器中，通过 getter() 方法获取数据，
     * 这样我们就可以获取到 easyexcel帮我们解析好的数据，再将数据进行类型转化，这样就可以对数据进行写入操作.
     *
     * @Author hejiayao
     * @Description //TODO 数据封装到 list中
     * @method invoke
     * @Date 14:19 2021/7/5
     * @param qualityUser
     * @param analysisContext
     * @return void
     **/
    @Override
    public void invoke(QualityUser qualityUser, AnalysisContext analysisContext) {
        log.info(JSON.toJSONString(qualityUser));
        if (StringUtils.isBlank(qualityUser.getQualityNum())) {
            String message = "质检订单号为空";
            errDate(qualityUser, message);
            return;
        }
        if (StringUtils.isBlank(qualityUser.getAuditNum())) {
            String message = "审核订单号为空";
            errDate(qualityUser, message);
            return;
        }
        if (StringUtils.isBlank(qualityUser.getOrderUserDep())) {
            String message = "订单归属部门为空";
            errDate(qualityUser, message);
            return;
        }
        if (StringUtils.isBlank(qualityUser.getQualityNoConforCauseId())) {
            String message = "不合规原因为空";
            errDate(qualityUser, message);
            return;
        }
        if (StringUtils.isBlank(qualityUser.getCheckoutRemark())) {
            String message = "质检备注为空";
            errDate(qualityUser, message);
            return;
        }
        if (StringUtils.isBlank(qualityUser.getQualityTime())) {
            String message = "质检时间为空";
            errDate(qualityUser, message);
            return;
        }
        qualityUserList.add(qualityUser);
    }


    /**
     * @Author hejiayao
     * @Description //TODO 封装错误信息返回值
     * @method errDate
     * @Date 14:19 2021/7/5
     * @param qualityUser
     * @param message
     * @return void
     **/
    private void errDate(QualityUser qualityUser, String message) {
        response.setStatus(Constant.NOT_XLSX_PARAM_USER_CODE);
        response.setMessage(message);
        errList.add(qualityUser);
        if (!errMessage.toString().contains(message)) {
            errMessage.append(message);
            errMessage.append(StrUtil.CRLF);
        }
    }

    /**
     * @Author hejiayao
     * @Description //TODO 所有都解析完毕后要执行的操作
     * @method doAfterAllAnalysed
     * @Date 14:19 2021/7/5
     * @param analysisContext
     * @return void
     **/
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        LOGGER.info("开始导入数据");
        LOGGER.info("全部数据 ： {}", JSON.toJSONString(qualityUserList));
        int up = qualityUserService.inserBatch(qualityUserList);
        //导入信息返回值
        //总数 成功数 失败数 失败集合 失败信息
        int err = errList.size();

        int totalCount = err + up;

        excelInfo.setTotal(totalCount);
        excelInfo.setErr(err);
        excelInfo.setSuccess(up);
        excelInfo.setErrList(errList);
        excelInfo.setErrMessage(errMessage.toString());
        response.setData(excelInfo);
    }


    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        throw exception;
    }

}
